package com.kmb.business.controller;

import com.kmb.commons.dto.Page;
import com.kmb.commons.dto.Response;
import com.kmb.commons.utils.DateUtil;
import com.kmb.commons.utils.HttpUtils;
import com.kmb.provider.api.SfKmDownloadService;
import com.kmb.provider.api.SfKmSourceService;
import com.kmb.provider.domain.SfKmDownload;
import com.kmb.provider.domain.SfKmSource;
import com.kmb.provider.dto.MaterialsEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackgeName: com.kmb.business.controller
 * @ClassName: ShareController
 * @Author: Administrator
 * Date: 2020/2/14 0014 16:47
 * project name: kmb_boot_plus
 * @Version:
 * @Description:
 */
@Slf4j
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "share")
public class ShareController {
    @Reference(version = "1.0.0")
    private SfKmSourceService sfKmSourceService;

    @Reference(version = "1.0.0")
    private SfKmDownloadService sfKmDownloadService;

    /**
     * 发布资料
     *
     * @param materialsEntity
     * @return
     */
    @PostMapping("addMaterials")
    public Response addMaterials(@RequestBody MaterialsEntity materialsEntity) {
        // 获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        materialsEntity.setCreateUser(authentication.getName());
        SfKmSource sfKmSource = new SfKmSource();
        BeanUtils.copyProperties(materialsEntity, sfKmSource);
        sfKmSource.setLabel(StringUtils.join(materialsEntity.getLabel(), ","));
        int id = sfKmSourceService.addMaterials(sfKmSource);
        return Response.ok(id);
    }

    /**
     * 获取最新的资料列表（只获取开发资料）
     *
     * @return
     */
    @GetMapping("getMaterials")
    public Response getMaterials(@RequestParam("sourceType") int sourceType, @RequestParam(value = "keyword", required = false) String keyword, boolean allData, Page page) {
        List<SfKmSource> materialsEntityList = sfKmSourceService.getMaterials(sourceType, keyword, allData, page);
        Map<String, Object> result = new HashMap<>();
        result.put("materialsEntityList", materialsEntityList);
        return Response.ok(result, page);
    }

    /**
     * 根据url下载
     *
     * @param url
     */
    @GetMapping("downloadFileFromURL")
    public void downloadFileFromURL(HttpServletResponse response, @RequestParam("url") String url, @RequestParam("sourceId") int sourceId) {
        try {
            // 获取认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            // 设置下载参数
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            HttpUtils.httpGetToFile(null, url, response.getOutputStream());
            // 记录下载
            SfKmDownload sfKmDownload = new SfKmDownload();
            sfKmDownload.setSourceId(sourceId);
            sfKmDownload.setCreateTime(String.valueOf(DateUtil.getCurrentLongTime()));
            sfKmDownload.setCreateUser(authentication.getName());
            sfKmDownload.setUpdateTime(String.valueOf(DateUtil.getCurrentLongTime()));
            sfKmDownload.setUpdateUser(authentication.getName());
            sfKmDownloadService.addDowload(sfKmDownload);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("下载文件异常", e);
        }
    }
}
